<template>
    <div>
        <ConditionCard
            body-style="padding: 24px"
            class="groupList-addUser"
            @search="queryTableList"
            @reset="reset"
        >
            <el-form ref="queryForm" :model="queryForm" label-width="80px" label-suffix="：">
                <el-row :gutter="2">
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.yearAndSemester')">
                            <CalendarSelect
                                v-model="queryForm.condition.calendarId"
                            ></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.auditStatus')">
                            <DictSelect
                                labelAll="请选择"
                                v-model="queryForm.condition.status"
                                :data="options.status"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card>
            <h1 slot="header">{{$t('exchangeApproval.exchangeApplicationList')}}</h1>
            <el-row type="flex" justify="space-between" align="center" style="margin-bottom:16px">
                <el-col :span="6">
                    <KeywordInput v-model="keyWord" :placeholder="$t('exchangeApproval.searchName')" @enter="handleClick" />
                </el-col>
                <el-col :span="6" style="text-align:right">
                    <el-button type="primary" @click="handleClick('ADD')">{{$t('exchangeApproval.apply')}}</el-button>
                </el-col>
            </el-row>
            <edu-table
                :data="tableList"
                :selection="false"
                :total="queryForm.total_"
                :pageSize="queryForm.pageSize_"
                @page-change="onCurrentPageChange"
            >
                <el-table-column  :label="$t('exchangeApproval.studentNumber')" prop="studentId" width="80"></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.fullName')"
                    prop="studentName"
                    width="80"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.yearAndSemester')"
                    prop="calendarName"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangeName')"
                    prop="exchangesName"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.schoolName')"
                    prop="exchangesUniversityNameZH"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangesStartTime')"
                    prop="exchangesStartTime"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangesEndTime')"
                    prop="exchangesEndTime"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.applicationDate')"
                    prop="createTime"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column :label="$t('exchangeApproval.auditStatus')">
                    <template slot-scope="scope">
                        <el-tag :type="getStatus(scope.row.status)['type']">
                            {{ getStatus(scope.row.status)['label'] }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('exchangeApproval.operate')" width="120">
                    <template slot-scope="scope">
                        <el-button type="text" @click="operate('VIEW', scope.row)">{{$t('exchangeApproval.check')}}</el-button>
                        <el-button
                            type="text"
                            v-if="!scope.row.status || scope.row.status == 2"
                            @click="operate('EDIT', scope.row)"
                        >
                             {{$t('exchangeApproval.edit')}}
                        </el-button> 
                        <el-button type="text" @click="operate('RECALL', scope.row)" v-if="scope.row.status == 4">{{$t('exchangeApproval.revoke')}}</el-button>
                        <el-button
                            :disabled="+scope.row.backType !== 1"
                            type="text"
                            v-if="+scope.row.status === 3  "
                            @click="operate('HOMEAPP', scope.row)"
                        >
                            {{$t('exchangeApproval.returnToSchoolApplication')}}
                        </el-button>
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>
        <el-dialog
            :title="dialog.mode == 'ADD' ? '申请' : '编辑'"
            :visible.sync="dialog.visiable"
            :close-on-click-modal="false"
            @close="dialogClose"
            @open="dialogOpen"
            width="60%"
        >
            <el-form
                label-suffix="："
                :model="dialog.applyParams"
                label-position="right"
                ref="dialog"
                label-width="150px"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.exchangeName')"
                            prop="exchangesName"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterExchangeName'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-input
                                v-model="dialog.applyParams.exchangesName"
                                :placeholder="$t('exchangeApproval.pleaseEnterExchangeName')"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.schoolName')"
                            prop="exchangesUniversity"
                            :rules="[{ required: true, message: this.$t('exchangeApproval.pleaseSelect'), trigger: 'change' }]"
                        >
                            <el-select
                                v-model="dialog.applyParams.exchangesUniversity"
                                :placeholder="$t('exchangeApproval.pleaseSelect')"
                                style="width:100%"
                                filterable
                                @change="unChange"
                            >
                                <el-option
                                    v-for="item in options.collegeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.exchangesCountry')"
                            prop="exchangesCountry"
                            :rules="[
                                { required: true, message: this.$t('exchangeApproval.pleaseEnterCountry'), trigger: 'blur' }
                            ]"
                        >
                            <el-input
                                v-model="dialog.applyParams.exchangesCountryI18n"
                                :placeholder="$t('exchangeApproval.pleaseEnterCountry')"
                                disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.natureOfCommunication')"
                            prop="exchangesNature"
                            :rules="[{ required: true, message: this.$t('exchangeApproval.pleaseSelect'), trigger: 'change' }]"
                        >
                            <el-select
                                v-model="dialog.applyParams.exchangesNature"
                                :placeholder="$t('exchangeApproval.pleaseSelect')"
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.exchangesNatureList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.startTime')"
                            prop="exchangesStartTime"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterStartTime'),
                                    trigger: 'change'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"
                                style="width:100%"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :placeholder="$t('exchangeApproval.selectDate')"
                                v-model="dialog.applyParams.exchangesStartTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.endTime')"
                            prop="exchangesEndTime"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterEndTime'),
                                    trigger: 'change'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"
                                style="width:100%"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :placeholder="$t('exchangeApproval.selectDate')"
                                v-model="dialog.applyParams.exchangesEndTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item
                        ref="exchangeCourseScheduleList"
                        :label="$t('exchangeApproval.exchangeSchedule')"
                        prop="attachmentCategoryDTO.exchangeCourseScheduleList"
                        :rules="[
                            {
                                required: true,
                                message: this.$t('exchangeApproval.pleaseUploadCourse'),
                                trigger: 'change'
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(
                                        response,
                                        file,
                                        fileList,
                                        'exchangeCourseScheduleList'
                                    )
                            "
                            :on-remove="
                                (file, fileList) =>
                                    handlerRemove(file, fileList, 'exchangeCourseScheduleList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="
                                dialog.applyParams.attachmentCategoryDTO.exchangeCourseScheduleList
                            "
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                    {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip" style="margin:0 0 0 5px;">
                                    {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button type="primary" @click="download">{{$t('exchangeApproval.downloadCourse')}}</el-button>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item
                        :label="$t('exchangeApproval.schoolApproval')"
                        ref="schoolCertificateList"
                        prop="attachmentCategoryDTO.schoolCertificateList"
                        :rules="[
                            {
                                required: true,
                                message: this.$t('exchangeApproval.pleaseUploadApproval'),
                                trigger: 'change'
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(
                                        response,
                                        file,
                                        fileList,
                                        'schoolCertificateList'
                                    )
                            "
                            :on-remove="
                                (file, fileList) =>
                                    handlerRemove(file, fileList, 'schoolCertificateList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="
                                dialog.applyParams.attachmentCategoryDTO.schoolCertificateList
                            "
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                     {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip" style="margin:0 0 0 5px;">
                                    {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button style="display:none" type="primary" @click="download">
                        {{$t('exchangeApproval.downloadCourse')}}
                    </el-button>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item :label="$t('exchangeApproval.other')">
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(response, file, fileList, 'otherAttachList')
                            "
                            :on-remove="
                                (file, fileList) => handlerRemove(file, fileList, 'otherAttachList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="dialog.applyParams.attachmentCategoryDTO.otherAttachList"
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                     {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip" style="margin:0 0 0 5px;">
                                    {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button style="display:none" type="primary" @click="download">
                        {{$t('exchangeApproval.downloadCourse')}}
                    </el-button>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialog.visiable = false">{{$t('exchangeApproval.cancel')}}</el-button>
                <el-button type="primary" @click="handleClickDlg('SAVE')">{{$t('exchangeApproval.save')}}</el-button>
                <el-button type="primary" @click="handleClickDlg('SUB')">{{$t('exchangeApproval.submit')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import UTILS from 'common/src/utils/utils'
import { queryDic } from 'common/src/api/dictionary'
import { getUS } from 'common/src/api/internationalExchanges/exchangeCollegeManagement'
import {
    applyList,
    downloadTemplate,
    saveApply,
    addApply,
    back,
    exchangeRecall
} from 'common/src/api/internationalExchanges/exchangeApplication'
import {
   getCourseTemplate
} from 'common/src/api/internationalExchanges/switchSetting'
import mixin from 'common/src/mixins/index';
export default {
    mixins: [mixin],
    data() {
        return {
            queryForm: {
                total_: 0,
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    calendarId: '',
                    status: '',
                    queryType: 0,
                    ids: []
                }
            },
            dialog: {
                visiable: false,
                mode: '',
                applyParams: {
                    id: '',
                    type: '0',
                    studentId: '',
                    studentName: '',
                    exchangesName: '',
                    exchangesUniversity: '',
                    exchangesCountry: '',
                    exchangesCountryI18n: '',
                    exchangesNature: '',
                    exchangesStartTime: '',
                    exchangesEndTime: '',
                    attachmentCategoryDTO: {
                        exchangeCourseScheduleList: [],
                        schoolCertificateList: [],
                        otherAttachList: []
                    }
                }
            },
            tableList: [],
            options: {
                collegeList: [],
                exchangesNatureList: [],
                status: [
                    {
                        value: 0,
                        label: '草稿',
                        type: 'info'
                    },
                    {
                        value: 1,
                        label: '审核中',
                        type: ''
                    },
                    {
                        value: 2,
                        label: '已驳回',
                        type: 'warning'
                    },
                    {
                        value: 3,
                        label: '已通过',
                        type: 'success'
                    },
                    {
                        value: 4,
                        label: '已提交',
                        type: 'success'
                    }
                ]
            }
        }
    },
    mounted() {
        let user = this.global.currentUser
        this.dialog.applyParams.studentId = user ? user.uid : ''
        this.dialog.applyParams.studentName = user ? user.name : ''
        this.queryTableList()
    },
    methods: {
        getStatus(type = 0) {
            let list = this.options.status
            let obj = list.find(item => item.value == type)
            return obj
        },
        async queryTableList(params = this.queryForm) {
            let { code, data } = await applyList(params)
            if (code !== 200) return
            this.tableList = data.list
            this.queryForm.total_ = data.total_
            this.queryForm.pageSize_ = data.pageSize_
        },
        onCurrentPageChange(pager) {
            this.queryForm.pageSize_ = pager.pageSize
            this.queryForm.pageNum_ = pager.pageNum
            this.queryTableList()
        },
        init() {
            //筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_JLXZ']
            }
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            exchangesNatureList: 'X_JLXZ'
                        },
                        res.data,
                        this.options
                    )
                }
            })
        },
        async queryCollegeList() {
            let params = {
                total_: 0,
                pageNum_: 1,
                pageSize_: 10000,
                condition: {}
            }
            let { code, data } = await getUS(params)
            if (code !== 200) return
            this.options.collegeList = data.list.map(item => {
                return {
                    label:
                        this.$store.getters.language == 'cn'
                            ? item.universityNameZN
                            : item.universityNameEN,
                    value: item.universityNameCode,
                    regionName:
                        this.$store.getters.language == 'cn'
                            ? item.regionNameZN
                            : item.regionNameEN,
                    regionCode: item.regionCode
                }
            })
        },
        handleClick(mode) {
            switch (mode) {
                case 'ADD':
                    !this.options.exchangesNatureList.length && this.init()
                    !this.options.collegeList.length && this.queryCollegeList()
                    this.dialog.mode = mode
                    this.dialog.visiable = !this.dialog.visiable
                    break
            }
        },
        //移除文件回调
        handlerRemove(file, fileList, mode) {
            let list = this.dialog.applyParams.attachmentCategoryDTO[mode]
            let index = list.findIndex(item => item.uid == file.uid)
            list.splice(index, 1)
            this.dialog.applyParams.attachmentCategoryDTO[mode] = list
        },
        //上传文件成功回调
        handlerSuccess(response, file, fileList, mode) {
            let responseCode = response.code
            let type
            if (mode == 'exchangeCourseScheduleList') {
                type = 1
            } else if (mode == 'schoolCertificateList') {
                type = 2
            } else {
                type = 3
            }
            if (responseCode === 200) {
                this.dialog.applyParams.attachmentCategoryDTO[mode].push({
                    type: type,
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
                let len = this.dialog.applyParams.attachmentCategoryDTO[mode]
                if (len.length > 0) this.$refs[mode].clearValidate()
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //上传文件失败回调
        handlerError(response, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.jpg,.png,.gif,.doc,.docx,.xlsx,.xls,.pdf',
                    size: '5'
                },
                this
            )
        },

        async submit(mode) {
            let request =
                mode == 'SAVE'
                    ? saveApply(this.dialog.applyParams)
                    : addApply(this.dialog.applyParams)
            let { code, data } = await request
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: mode == 'SAVE' ? '保存成功' : '新增成功'
            })
            this.dialog.visiable = !this.dialog.visiable
            this.queryTableList()
        },
        handleClickDlg(mode) {
            this.$refs['dialog'].validate(valid => {
                if (valid) {
                    this.submit(mode)
                } else {
                    return false
                }
            })
        },
        async download() {
            // 课程计划表模板下载
            // downloadTemplate()
            let param = {
                tempType: 0
            };
            let {code, data} = await getCourseTemplate(param);
            if (code == 200) {
                let [{objectKey}] = data || [{}];
                window.location.href = `/api/commonservice/obsfile/downloadfile?objectkey=${objectKey}`;
            }
           // window.location.href = `/api/externalexchangeservice/course/plan/download?tempType=0`;
        },
        unChange(val) {
            let obj = this.options.collegeList.find(item => item.value == val)
            this.dialog.applyParams.exchangesCountryI18n = obj ? obj.regionName : ''
            this.dialog.applyParams.exchangesCountry = obj ? obj.regionCode : ''
        },
        operate(mode, row) {
            let _row = _.cloneDeep(row)
            switch (mode) {
                case 'EDIT':
                    !this.options.exchangesNatureList.length && this.init()
                    !this.options.collegeList.length && this.queryCollegeList()
                    this.dialog.visiable = !this.dialog.visiable
                    this.dialog.mode = mode
                    this.dialog.applyParams.attachmentCategoryDTO = _row.attachmentCategoryDTO
                    for (let key in this.dialog.applyParams) {
                        if (key !== 'attachmentCategoryDTO' && key !== 'type') {
                            this.dialog.applyParams[key] = _row[key]
                        }
                    }
                    break
                case 'VIEW':
                    this.$router.push({
                        name: 'UGIEApprovalDetail',
                        params: {
                            data: _row,
                            mode
                        }
                    })
                    break
                case 'HOMEAPP':
                   let  _this = this;
                    _this.$confirm('是否继续返校申请?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                    .then(() => {
                        back(_row.id).then((res)=>{
                            if(res.code ==200){
                                res.msg && this.$message({
                                        type: 'success',
                                        message: res.msg
                                    })
                                _this.queryTableList()
                            }
                        })
                    })
                    break
                case 'RECALL':
                    this.$confirm('此操作将撤销此条审请记录, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        exchangeRecall(row.workflowNo).then(res =>{
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '撤销成功'
                                })
                                this.queryTableList();
                            }
                        })
                    })
                    break;
            }
        },
        dialogClose() {
            this.dialog.mode = ''
            for (let key in this.dialog.applyParams) {
                if (
                    key !== 'attachmentCategoryDTO' &&
                    key !== 'type' &&
                    key !== 'studentId' &&
                    key !== 'studentName'
                ) {
                    this.dialog.applyParams[key] = ''
                }
            }
            this.dialog.applyParams.attachmentCategoryDTO.exchangeCourseScheduleList = []
            this.dialog.applyParams.attachmentCategoryDTO.schoolCertificateList = []
            this.dialog.applyParams.attachmentCategoryDTO.otherAttachList = []
        },
        dialogOpen() {
            this.$refs['dialog'] && this.$refs['dialog'].clearValidate()
        },
        reset() {
            this.queryForm.total_ = 0
            this.queryForm.pageNum_ = 1
            this.queryForm.pageSize_ = 20
            this.queryForm.condition.status = ''
            this.queryTableList()
        }
    }
}
</script>

<style>
</style>
